package personal.lijun.skeleton.springcloud.utils.validate;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * @Auther: lijun@sstcsoft.com
 * @Date: 2019/9/11 15:06
 */
public class ValidationUtils {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> String validateEntity(T obj,Class ...groups){
        StringBuilder sb = new StringBuilder();
        Set<ConstraintViolation<T>> constraintViolationSet = validator.validate(obj,groups);
        Iterator<ConstraintViolation<T>> constraintViolationIterator = constraintViolationSet.iterator();
        while (constraintViolationIterator.hasNext()){
            ConstraintViolation<T> constraintViolation = constraintViolationIterator.next();
            sb.append(constraintViolation.getPropertyPath());
            sb.append(":");
            sb.append(constraintViolation.getMessage());
            sb.append("\r\n");
        }
        return sb.toString();
    }

    public static <T> String validateProperty(T obj, String propertyName,Class ...groups){
        StringBuilder sb = new StringBuilder();
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName,groups);
        Iterator<ConstraintViolation<T>> constraintViolationIterator = set.iterator();
        while (constraintViolationIterator.hasNext()){
            ConstraintViolation<T> constraintViolation = constraintViolationIterator.next();
            sb.append(constraintViolation.getPropertyPath());
            sb.append(":");
            sb.append(constraintViolation.getMessage());
            sb.append("\r\n");
        }
        return sb.toString();
    }
}
